# main.py - 修复主程序入口
import tkinter as tk
import logging
import sys
from pathlib import Path

from config import Config
from core.note_manager import NoteManager
from ui.main_window import MainWindow
from logger.logger import get_logger

def setup_logging(config):
    """设置日志系统"""
    logger = get_logger(config)
    logger.info("=" * 50)
    logger.info(f"{config.app_name} {config.version} 启动")
    logger.info("=" * 50)
    return logger

def handle_exception(exc_type, exc_value, exc_traceback):
    """全局异常处理"""
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return
    
    logger = get_logger()
    logger.error("未捕获的异常:", exc_info=(exc_type, exc_value, exc_traceback))

def main():
    """主程序入口"""
    try:
        # 创建配置
        config = Config()
        
        # 设置日志
        logger = setup_logging(config)
        
        # 设置全局异常处理
        sys.excepthook = handle_exception
        
        # 创建主窗口
        root = tk.Tk()
        
        # 创建笔记管理器
        note_manager = NoteManager(config, root)
        
        # 创建主窗口
        app = MainWindow(root, config, note_manager)
        
        # 启动主循环
        root.mainloop()
        
    except Exception as e:
        # 记录启动错误
        if 'logger' in locals():
            logger.exception("程序启动失败")
        else:
            print(f"程序启动失败: {e}")
        
        # 显示错误对话框
        try:
            error_msg = f"程序启动时发生错误:\n\n{str(e)}\n\n请检查配置和网络连接后重试。"
            tk.messagebox.showerror("启动错误", error_msg)
        except:
            pass
        
        sys.exit(1)

if __name__ == "__main__":
    main()